﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace Common
{
    /// <summary>
    /// 序列化与反序列化工具类
    /// </summary>
    public class SerializeHelper
    {
        /// <summary>
        /// 序列化对象
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>序列化后的字节数组</returns>
        public static byte[] Serialize(object obj)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            formatter.Serialize(ms, obj);
            return ms.ToArray();
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="bys">对象的字节数组</param>
        /// <returns>反序列化对象</returns>
        public static object Deserialize(byte[] bys)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream ms = new MemoryStream(bys);
            return formatter.Deserialize(ms);
        }
    }
}
